﻿using System;
using Microsoft.Practices.Unity;

namespace IOC
{
    /// <summary>
    /// UnityServiceLocator&lt;T&gt; provides a basic implementation of a service locator with singleton behaviour.
    /// Inherit from this class to provide your own, custom, service locator with the basic behaviour that UnityServiceLocator&lt;T&gt; provides
    /// </summary>
    /// <typeparam name="T">specifies which type is returned in the .Current property</typeparam>
    /// <example>
    /// MyServiceLocator : UnityServiceLocator&lt;MyServiceLocator&gt; 
    /// </example>
    public class UnityServiceLocator<T> where T : new()
    {


        private int i = 0;
        private DateTime when;

        public string ConstructorInfo 
        { 
            get 
            { 
                return string.Format("UnityServiceLocator: number of calls to constructor {0}. Called at {1}",  i, when); 
            } 
        }

        private IUnityContainer container;

        /// <summary>
        /// Needed for inheritance
        /// </summary>
        protected UnityServiceLocator()
        {
            when = DateTime.Now;
            i++;

            EnsureContainer();
        }


        private void EnsureContainer()
        {
            if (container == null)
            {
                container = new UnityContainer();
            }
        }


        public static T Current
        {
            get
            {
                return Singleton.Instance;
            }
        }


        class Singleton
        {
            static Singleton() { }
            internal static readonly T Instance = new T();
        }

    }
}
